package com.atguigu.gmall.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.IpUtil;
import com.atguigu.gmall.model.list.Goods;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.service.UserService;
import com.baomidou.mybatisplus.core.conditions.interfaces.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 * 用户认证接口
 * </p>
 */
@RestController
@RequestMapping("/api/user/passport")
public class PassportApiController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录
     *
     * @param userInfo
     * @param request
     * @param response
     * @return
     */
    @PostMapping("login")
    public Result login(@RequestBody UserInfo userInfo, HttpServletRequest request, HttpServletResponse response) {
        //查询数据库
        UserInfo info  = userService.login(userInfo);
        if (info!=null){
            HashMap<String, Object> map = new HashMap<>();
            //生成token
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            map.put("nickName", info.getNickName());
            map.put("token", token);

            JSONObject jsonObject=new JSONObject();
            jsonObject.put("userId",info.getId().toString());
            //防止token被盗用加ip
            jsonObject.put("ip", IpUtil.getIpAddress(request));

            //放入redis
            redisTemplate.opsForValue().set(RedisConst.USER_LOGIN_KEY_PREFIX+token,jsonObject.toJSONString(),RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);
            return Result.ok(map);
        }else {
            return Result.fail().message("用户名或密码错误");
        }
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
    @GetMapping("logout")
    public Result logout(@RequestHeader String token, HttpServletRequest request) {
        //删除请求头中的token信息
//       redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+request.getHeader("token"));
       redisTemplate.delete(RedisConst.USER_LOGIN_KEY_PREFIX+token);
       return Result.ok();
    }
}